<template>
  <ele-page flex-table :multi-card="false" hide-footer>
    <region-search
      @search="reload"
      :cache-key="getCurrentInstance().type.name"
    />
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
      hide-footer
    >
      <ele-pro-table
        sticky
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        :highlight-current-row="true"
        :export-config="{ fileName: '地区数据' }"
        :default-expand-all="false"
        :pagination="false"
        virtual
        cache-key="BaseRegionTable"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="ColumnHeightOutlined"
            @click="expandAll"
          >
            展开全部
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="VerticalAlignMiddleOutlined"
            @click="foldAll"
          >
            折叠全部
          </el-button>
        </template>

        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openAdd(row)">
            添加
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openView(row)">
            查看
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            underline="never"
            @click="action('remove', row)"
          >
            删除
          </el-link>

          <!-- 
            <el-link
              type="primary"
              underline="never"
              @click="openEdit(null, row.region_id)"
            >
              添加
            </el-link>
            <el-divider direction="vertical" />
            <el-link type="primary" underline="never" @click="openEdit(row)">
              修改
            </el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" underline="never" @click="remove(row)">
              删除
            </el-link> -->
        </template>
      </ele-pro-table>
    </ele-card>

    <!-- 新增 -->
    <region-edit
      ref="regionEditRef"
      :parentCode="parent_code"
      action="add"
      v-model="showAdd"
      @done="handleRegionEditDone"
    />

    <!-- 修改 -->
    <region-edit
      action="edit"
      ref="regionEditRef"
      :parentCode="parent_code"
      :data="current"
      v-model="showEdit"
      @done="handleRegionEditDone"
    />

    <!-- 查看 -->
    <region-edit
      action="view"
      ref="regionEditRef"
      :parentCode="parent_code"
      :data="current"
      v-model="showView"
      @done="handleRegionEditDone"
    />
  </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";

import { toTree } from "ele-admin-plus/es";
import {
  PlusOutlined,
  ColumnHeightOutlined,
  VerticalAlignMiddleOutlined,
} from "@/components/icons";
import RegionSearch from "./components/region-search.vue";
import RegionEdit from "./components/region-edit.vue";
import { listRegions, removeRegions } from "@/api/base/region";
import { useTable } from "@/hooks/useTable";
import { useOperator } from "@/hooks/operator";

import { useModal } from "@/hooks/useModal";

defineOptions({ name: "BaseRegionTable" });

// 递归添加父节点信息
const addParentInfo = (nodes, allData) => {
  nodes.forEach((node) => {
    if (node.parent_code) {
      // 获取所有父级节点信息（包括省、市）
      const getParentChain = (id, chain = []) => {
        const parent = allData.find((item) => item.id === id);
        if (parent) {
          chain.push({
            id: parent.id,
            name: parent.name,
            parent_code: parent.parent_code,
            level: parent.level,
          });
          // 继续查找上级
          if (parent.parent_code) {
            return getParentChain(parent.parent_code, chain);
          }
        }
        return chain;
      };

      node.parentChain = getParentChain(node.parent_code).reverse(); // 反转数组使顺序从高到低
    }
    if (node.children) {
      addParentInfo(node.children, allData);
    }
  });
};
// 使用 useTable
const { tableRef, datasource, reload, expandAll, foldAll } = useTable({
  getPages: listRegions,
  afterQuery: (data) => {
    addParentInfo(data, data);
    // 先转换为树形结构
    let result = toTree({
      data,
      idField: "id",
      parentIdField: "parent_code",
    });

    console.log("result", result);
    return result;
  },
});

// 使用 useOperator 处理删除操作
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      api: removeRegions,
      confirmText: "确定要删除“{%s}”吗?",
      beforeSubmit: ({ type, rows, formData }) => {
        if (rows[0].children?.length) {
          return new Error("请先删除子节点");
        }
        return { type, rows, formData };
      },
    },
  },
  idField: "id",
  idName: "name",
  reload,
});

// 表格列配置
const columns = ref([
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "name",
    label: "地区名称",
    slot: "name",
    minWidth: 160,
  },
  {
    prop: "allname",
    label: "地区全称",
    slot: "nameall",
    minWidth: 160,
    formatter: (row) => {
      if (!row.parentChain || row.parentChain.length === 0) return row.name;
      const parentNames = row.parentChain.map((p) => p.name);
      return [...parentNames, row.name].join("/");
    },
  },
  {
    prop: "sort_number",
    label: "排序",
    width: 100,
    align: "center",
  },
  {
    prop: "status",
    label: "状态",
    width: 100,
    align: "center",
    formatter: (row) => ["禁用", "启用"][row.status],
  },

  {
    columnKey: "action",
    label: "操作",
    width: 180,
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
  },
]);

// 当前编辑数据
const current = ref(null);

// 上级菜单id
const parent_code = ref();

// 菜单编辑弹窗组件
const regionEditRef = ref(null);

// 刷新菜单下拉选择数据
const reloadRegionSelectData = () => {
  regionEditRef.value?.reloadRegionSelectData?.();
};

// 菜单编辑完成事件
const handleRegionEditDone = () => {
  reload();
  reloadRegionSelectData();
};

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: (row) => {
    console.log("新增前处理", row);
    parent_code.value = row?.id || 0; // 确保parent_code有默认值
    console.log("新增前处理", parent_code.value);
    current.value = null; // 重置current
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    // 更新useModal中的current值
    current.value = row; // 重置current
  },
});

const { visible: showView, open: openView } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
  },
});
</script>
